<template>
  <div
    class="goods-list-container list-container"
    v-loading.fullscreen.lock="loading"
  >
    <div
      ref="tableHeaderContainer"
      class="goods-list-search-group-container bg-w list-search-group-container"
      style="display: block"
    >
      <div class="task-list-header-search" style="align-items: center">
        <form class="task-flex task-ai" onsubmit="return false;">
          <div
            class="base-search-group input-with-append-search task-flex task-ai"
          >
            <el-input
              v-model="searchModel.keyword"
              :placeholder="$t('member.list.title1')"
              class="task-with-input task-mr12"
            >
              <i slot="prefix" class="el-input__icon el-icon-search"></i>

              <el-button
                type="primary"
                slot="append"
                @click="
                  searchModel.pageNum = 1;
                  handleSearch();
                "
                native-type="submit"
              >
                {{$t('common.base.search')}}
              </el-button>
            </el-input>
            <el-button type="plain-third" @click="resetParams">{{$t('common.base.reset')}}</el-button>
          </div>

          <!-- 老版本高级搜索 -->
          <div class="base-search">
            <div
              @click.self.stop="panelSearchAdvancedToggle"
              class="advanced-search-visible-btn"
            >
              <i class="iconfont icon-filter task-mr4"></i>
              {{$t('common.base.advancedSearch')}}
            </div>
          </div>
        </form>
      </div>
    </div>

    <!-- 图表区域 -->
    <div class="goods-list-section list-section">
      <div ref="tableDoContainer" class="operation-bar-container">
        <!-- 按钮区域 -->
        <div class="top-btn-group flex-x">
          <el-button type="primary" v-if="createPermission" @click="handleCreate">
            <i class="iconfont icon-add2"></i>{{$t('common.base.create')}}
          </el-button>

          <el-button
            type="plain-third"
            v-if="deletePermission"
            @click="handleDelete"
          >
            <i class="iconfont icon-delete"></i>{{$t('common.base.delete')}}
          </el-button>
        </div>

        <!-- 更多操作区域 -->
        <div class="action-button-group flex-x bg-w">
          <el-dropdown
            trigger="click"
            v-if="exportImportPermission"
          >
            <div
              class="task-ai task-flex task-font14 task-c6 cur-point bg-w"
            >
              <span class="task-mr4 task-ml4">{{$t('common.base.moreOperator')}}</span>
              <i class="iconfont icon-fdn-select"></i>
            </div>
            <el-dropdown-menu slot="dropdown">
              <template>
                <el-dropdown-item>
                  <div @click="importMember">{{ $t('common.base.import') }}</div>
                </el-dropdown-item>
                <el-dropdown-item>
                  <div @click="handleExport(false)">{{$t('common.base.export')}}</div>
                </el-dropdown-item>
                <el-dropdown-item>
                  <div @click="handleExport(true)">{{$t('common.base.exportAll')}}</div>
                </el-dropdown-item>
              </template>
            </el-dropdown-menu>
          </el-dropdown>

          <!-- 选择列 -->
          <div class="guide-box">
            <div
              class="task-ai task-flex task-font14 cur-point task-c6 task-width103  bg-w"
              @click="handleOpenSelectColumn"
            >
              <span class="task-mr4">{{$t('common.base.choiceCol')}}</span>
              <i class="iconfont icon-fdn-select"></i>
            </div>
          </div>
        </div>
      </div>

      <div class="bg-w pad-l-16 pad-r-16">
        <el-table
          v-table-style
          stripe
          :data="page.list"
          :highlight-current-row="false"
          :key="tableKey"
          :row-key="getRowKey"
          :border="true"
          @select="handleSelection"
          @select-all="handleSelection"
          @header-dragend="headerDragend"
          class="task-list-table common-list-table bg-w bbx-normal-list-box goods-table"
          header-row-class-name="common-list-table-header taks-list-table-header"
          :height="tableContainerHeight"
          ref="multipleTable"
        >
          <template slot="empty">
            <BaseListForNoData
              v-show="!loading"
              :notice-msg="$t('common.base.noData')"
            ></BaseListForNoData>
          </template>
          <el-table-column type="selection" align="center"></el-table-column>
          <template v-for="(column, index) in columns">
            <el-table-column
              v-if="column.show"
              :key="`${column.field}_${index}`"
              :label="column.label"
              :prop="column.field"
              :width="column.width"
              :min-width="column.minWidth || '120px'"
              :sortable="column.sortable"
              :fixed="column.fixLeft || false"
              :align="column.align"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                <template v-if="column.field === 'cardNo'">
                  <a
                    href=""
                    class="view-detail-btn"
                    @click.stop.prevent="handleOpenMemberDetail(scope.row)"
                  >
                    {{ scope.row.cardNo }}
                  </a>
                </template>
                <template v-else-if="column.field === 'customer'">
                  <a
                    href=""
                    class="view-detail-btn"
                    @click.stop.prevent="handleOpenCustomerTab(scope.row)"
                  >
                    {{ scope.row.customerName }}
                  </a>
                </template>
                <template v-else-if="column.field === 'limitEffectTime'">
                  {{ scope.row.limitEffectTime | fmt_form_date }} {{$t('common.base.to')}} {{ scope.row.limitExpirationTime | fmt_form_date }}
                </template>
                <template v-else-if="column.field === 'cardTypeId'">
                  {{ scope.row.cardTypeName }}
                </template>
                <template v-else-if="column.field === 'enabled'">
                  <el-switch
                    :value="scope.row.enabled"
                    @change="(val) => handleSwitchChange(scope.row, val)"
                    :active-text="scope.row.enabled ? $t('common.base.enable') : $t('common.base.disable')"
                    :active-value="1"
                    :inactive-value="0"
                  />
                </template>
                <template v-else>
                  {{
                    $formatFormField(column, scope.row)
                  }}
                </template>
              </template>
            </el-table-column>
          </template>
          <el-table-column fixed="right" :label="$t('common.base.operation')" width="120">
            <template slot-scope="scope">
              <el-dropdown class="dropdown" v-if="editPermission || deletePermission || memberOperatePermission">
                <span class="cur-point more-text">
                  {{$t('common.base.more')}}<i class="el-icon-arrow-down el-icon--right"></i>
                </span>
                <el-dropdown-menu slot="dropdown" class="lang-select-dropdown">
                  <el-dropdown-item><div v-if="memberOperatePermission && pointsEnable" @click="recharge(scope.row, 'point')">{{$t('member.components.title43')}}</div></el-dropdown-item>
                  <el-dropdown-item><div v-if="memberOperatePermission && serviceFeeEnable" @click="recharge(scope.row, 'serviceFee')">{{$t('member.components.title44')}}</div></el-dropdown-item>
                  <el-dropdown-item><div v-if="memberOperatePermission && balanceEnable" @click="recharge(scope.row, 'balance')">{{$t('member.components.title45')}}</div></el-dropdown-item>
                  <el-dropdown-item><div v-if="memberOperatePermission && pointsEnable" @click="consume(scope.row, 'point')">{{$t('member.components.title54')}}</div></el-dropdown-item>
                  <el-dropdown-item><div v-if="memberOperatePermission && balanceEnable" @click="consume(scope.row, 'balance')">{{$t('member.components.title55')}}</div></el-dropdown-item>
                  <el-dropdown-item><div v-if="editPermission" @click="editMember(scope.row)">{{$t('common.base.edit')}}</div></el-dropdown-item>
                  <el-dropdown-item><div v-if="deletePermission" @click="deleteMember(scope.row)">{{$t('common.base.delete')}}</div></el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页区域 -->
      <div
        ref="tableFooterContainer"
        class="table-footer bbx-normal-table-footer-10"
      >
        <div class="list-info">
          {{$t('goods.list.total')}} <span class="level-padding">{{ page.totalElements }}</span> {{$t('common.base.record')}}
          <template v-if="multipleSelection && multipleSelection.length > 0">
            {{$t('part.list.text2')}}
            <span
              class="product-selected-count"
              @click="multipleSelectionPanelShow = true"
              >{{ multipleSelection.length }}</span
            >{{$t('common.base.piece')}}
            <span class="product-selected-count" @click="toggleSelection()"
              >{{$t('common.base.clear')}}</span
            >
          </template>
        </div>
        <el-pagination
          class="product-table-pagination"
          background
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
          :page-sizes="[10, 20, 50]"
          :page-size="page.pageSize"
          :current-page="page.pageNum"
          layout="prev, pager, next, sizes, jumper"
          :total="page.totalElements"
        >
        </el-pagination>
      </div>
    </div>

    <!-- 导出弹窗 -->
    <base-export-group
      ref="exportPanelRef"
      :alert="exportAlert"
      :columns="exportColumns"
      :build-params="buildExportParams"
      :group="true"
      :validate="checkExportCount"
      :needchoose-break="false"
      method="post"
      :action="memberExport"
      :is-show-export-tip="isOpenData"
    />
    <!--  -->
    <base-import :title="$t('member.list.title2')"
      ref="importMemberModal"
      @success="handleSearch"
      :action="memberImport">
      <div slot="tip">
        <div class="base-import-warn">
          <p>
            <i18n path="common.base.importModal.downloadTemplateTip" tag="span">
              <a place="link" :href="memberTemplateImport">{{$t('common.base.importModal.importTemplate')}}</a>
            </i18n>
          </p>
        </div>
      </div>
    </base-import>

    <!-- 老版本高级搜索-->
    <base-search-drawer
      :show.sync="visible"
      @reset="resetParams"
      @search="handleAdvancedSearch"
      @changeWidth="setAdvanceSearchColumn"
    >
      <base-search-panel
        ref="searchPanel"
        :column-num="columnNum"
        :fields="searchFieldInfo"
      />
    </base-search-drawer>

    <!-- 选择列弹窗 -->
    <biz-select-column
      ref="selectColumnRef"
      mode="goods"
      :sotrage-key="'goods_select_column'"
      @save="saveColumnStatus"
    />

    <recharge-balance-dialog 
      ref="rechargeBalanceDialog"
      @updateList="handleSearch"
    />
    <recharge-serviceFee-dialog
      ref="rechargeServiceFeeDialog"
      @updateList="handleSearch"
    />
    <recharge-dialog 
      ref="rechargeDialog"
      @updateList="handleSearch"
    />
    <ConsumeDialog 
      ref="consumeDialogRef"
      @updateList="handleSearch"
    />
  </div>
</template>

<script>
import _ from 'lodash';
import { memberExport } from '@src/api/Export';
import { storageGet, storageSet } from '@src/util/storageV2';
import { openAccurateTab, isOpenData } from '@src/util/platform';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import { formatDate } from 'pub-bbx-utils';
import { safeNewDate } from '@src/util/time';
import AdvancedSearch from '@src/component/AdvancedSearch/index.vue';

import BaseSearchDrawer from 'packages/BaseSearchDrawer';
import BaseSearchPanel from 'packages/BaseSearchPanel';
import Page from '@model/Page';
import { getMemberFields } from '@src/modules/member/field.js';
import { memberTemplateImport, memberImport } from '@src/api/Import';
import RechargeDialog from '../components/RechargeDialog';
import RechargeBalanceDialog from '../components/RechargeBalanceDialog';
import RechargeServiceFeeDialog from '../components/RechargeServiceFeeDialog';
import ConsumeDialog from '@src/modules/member/components/ConsumeDialog.vue';
import { memberList, memberDelete } from '@src/api/Member'
import AuthUtil from '@src/util/auth';
import AuthMixin from '@src/mixins/authMixin';
import AuthEnum from '@model/enum/AuthEnum.ts';
import memberMixin from '../mixins/memberMixin';
import { editMembershipEnabled } from '@src/api/Member.ts'
export default {
  mixins: [AuthMixin, memberMixin],
  components: {
    AdvancedSearch, // 新版本高级筛选
    BaseSearchDrawer, // 老版本高级筛选
    BaseSearchPanel,
    RechargeDialog,
    RechargeBalanceDialog,
    RechargeServiceFeeDialog,
    ConsumeDialog,
  },
  data() {
    return {
      loading: true,
      page: new Page(),
      searchModel: {
        keyword: '',
        pageSize: 10,
        pageNum: 1,
      },
      multipleSelection: [],
      multipleSelectionPanelShow: false,
      columns: [],
      tableKey: (Math.random() * 1000) >> 2,
      tableContainerHeight: '440px',
      selectedLimit: 500,
      isOpenData,
      visible: false,
      columnNum: 1,
      memberExport,
      memberFields: [],
      advancedSearchParams: {},
      memberTemplateImport, 
      memberImport,
    };
  },
  computed: {
    createPermission() {
      return AuthUtil.hasAuth(this.globalLoginUserAuth, AuthEnum.MEMBER_CREATE);
    },
    editPermission() {
      return AuthUtil.hasAuth(this.globalLoginUserAuth, AuthEnum.MEMBER_EDIT);
    },
    deletePermission() {
      return AuthUtil.hasAuth(this.globalLoginUserAuth, AuthEnum.MEMBER_DELETE);
    },
    exportImportPermission() {
      return AuthUtil.hasAuth(this.globalLoginUserAuth, AuthEnum.MEMBER_IMPORT_EXPORT);
    },
    memberOperatePermission() {
      return AuthUtil.hasAuth(this.globalLoginUserAuth, AuthEnum.MEMBER_PROPERTY_OPERATE);
    },
    searchFieldInfo() {
      const searchGoodsFields = this.memberFields.filter(v => v.isSearch);

      return searchGoodsFields || []
    },
    // TODO 按钮权限控制
    getRowKey(row) {
      return row.id || '';
    },
    exportColumns() {
      let exportColumns = this.memberFields.filter(v => v.export);
      exportColumns = exportColumns.map(v => {
        v.exportAlias = v.displayName == this.$t('common.fields.customerName.displayName') ? 'customerName' : v.fieldName
        return {
          ...v, 
          label: v.displayName,
        }
      });

      let arr = [
        {
          label: this.$t('member.components.title46'),
          value: 'memberExport',
          columns: exportColumns,
        },
      ];
      return arr;
    },
    selectedIds() {
      return this.multipleSelection.map(v => v.id) || [];
    },
  },
  async mounted() {
    const { memberFields } = await getMemberFields();
    this.memberFields = memberFields || [];

    this.handleReloadPage();

    let that_ = this;
    // 监听切换后需要重新计算列表高度
    window.addEventListener('message', event => {
      const { action, data } = event.data;
      if (action == 'shb.frame.activatedPage') {
        that_.$nextTick(() => {
          that_.knowTableContainerHeight();
        });
      }
    });
    this.$nextTick(() => {
      this.knowTableContainerHeight();
      window.onresize = _.debounce(() => {
        that_.knowTableContainerHeight();
      }, 500);
    });
  },
  methods: {
    handleOpenMemberDetail(row) {
      let fromId = window.frameElement.getAttribute('id');
      let memberId = row.id
      if(!memberId) return 
      openAccurateTab({
        type: PageRoutesTypeEnum.PageMemberDetail,
        key: memberId,
        params: `id=${memberId}`,
        fromId
      })
    },
    handleOpenCustomerTab(row) {
      let fromId = window.frameElement.getAttribute('id');
      let customerId = row.customerId
      if(!customerId) return 
      openAccurateTab({
        type: PageRoutesTypeEnum.PageCustomerView,
        key: customerId,
        params: 'noHistory=1',
        fromId
      })
    },
    handleCreate() {
      openAccurateTab({
        type: PageRoutesTypeEnum.PageMemberCreate,
      });
    },
    importMember() {
      this.$refs.importMemberModal.open();
    },
    recharge(row, type) {
      if(type == 'balance') {
        this.$refs.rechargeBalanceDialog.open(row)
      }else if(type == 'point'){
        this.$refs.rechargeDialog.open(row, type)
      }else {
        this.$refs.rechargeServiceFeeDialog.open(row, type)
      }
    },
    consume(row, type) {
      if (!row.id) return;

      this.$refs.consumeDialogRef.open(row, type);
    },
    editMember(val) {
      let fromId = window.frameElement.getAttribute('id');
      let memberId = val.id
      openAccurateTab({
        type: PageRoutesTypeEnum.PageMemberEdit,
        params: `id=${memberId}`,
        fromId,
      });
    },
    async deleteMember(row) {
      let idList = [row.id]
      const { code, message } = await memberDelete(idList);
      if(code !== 0) return this.$message.error(message);
      this.handleSearch()
    },
    async handleSearch() {
      try {
        this.loading = true;
        const params = {
          ...this.searchModel,
          ...this.advancedSearchParams,
        };
        if (params.cardTypeId) {
          params.cardTypeIdList = params.cardTypeId
          delete params.cardTypeId
        }
        const { code, result } = await memberList(params);

        if (code !== 0) {
          this.loading = false;
          this.page = this.$options.data.call(this).page;
          return this.$message.error(this.$t('goods.tips.queryListFailed'));
        }
        const { pageNum, list, total, pageSize } = result;
        [
          this.page['list'],
          this.page['totalElements'],
          this.page['pageNum'],
          this.page['pageSize'],
        ] = [list, total, pageNum, pageSize];

        this.loading = false;
        this.matchSelected();
      } catch (error) {
        this.loading = false;
        console.error('fetch goods list error', error);
      }
    },
    reloadPage() {
      this.multipleSelection = [];
      this.$refs.multipleTable.clearSelection();
      this.handleSearch();
    },
    resetParams() {
      const option = this.$options.data.call(this);
      this.searchModel = option.searchModel;
      this.page = option.page;
      this.$refs.searchPanel?.initFormVal();
      this.advancedSearchParams = {};
      this.visible = false
      this.handleSearch();
    },
    handleReloadPage() {
      this.buildColumns();

      this.handleSearch();
    },
    // 老版本高级搜索 ——> 点击搜索按钮
    handleAdvancedSearch() {
      this.searchModel.pageNum = 1;
      // 获取高级搜索参数
      this.advancedSearchParams = this.$refs.searchPanel?.buildParams() || {};
      this.visible = false
      this.handleSearch();
    },
    panelSearchAdvancedToggle() {
      this.visible = true;
    },
    
    /** 设置高级搜索展示列数 */
    setAdvanceSearchColumn(command) {
      this.columnNum = Number(command);
    },
    async handleDelete() {
      if (!this.multipleSelection.length) {
        return this.$platform.alert(this.$t('member.list.title4'));
      }

      try {
        if (!(await this.$platform.confirm(this.$t('member.list.title5')))) return;
        this.loading = true;

        const ids = this.multipleSelection.map(p => p.id);
        const { code, message } = await memberDelete(ids);
        this.loading = false;

        if (code !== 0) {
          return this.$message.error(message || this.$t('common.base.deleteFail'));
        }
        this.$message.success(this.$t('common.base.deleteSuccess'));

        this.multipleSelection = [];
        setTimeout(() => {
          this.handleSearch();
        }, 1000);
      } catch (error) {
        this.loading = false;
        console.error('error', error);
      }
    },
    handleExport(exportAll) {
      let ids = [];
      let fileName = `${formatDate(safeNewDate(), 'YYYY-MM-DD')}会员数据.xlsx`;
      if (!exportAll) {
        if (!this.multipleSelection.length)
          return this.$platform.alert(this.$t('common.base.tip.exportNoChoice'));
        ids = this.selectedIds;
      }
      this.$refs.exportPanelRef.open(ids, fileName);
    },
    /**
     * @description 导出提示
     */
    exportAlert(result, params = {}) {
      this.$platform.alert(result.message);
    },
    handleOpenSelectColumn() {
      this.$refs.selectColumnRef.open(this.columns);
    },
    handleSelection(selection) {
      let tv = this.selectionCompute(selection);

      let original = this.multipleSelection.filter(ms =>
        this.page.list.some(cs => cs.id === ms.id)
      );

      let unSelected = this.page.list.filter(c =>
        original.every(oc => oc.id !== c.id)
      );

      if (tv.length > this.selectedLimit) {
        this.$nextTick(() => {
          original.length > 0
            ? unSelected.forEach(row => {
                this.$refs.multipleTable.toggleRowSelection(row, false);
              })
            : this.$refs.multipleTable.clearSelection();
        });
        return this.$platform.alert(this.$t('common.base.tip.maxDataCanChooseTips', {data1: this.selectedLimit}));
      }

      this.multipleSelection = tv;

      // this.$refs.baseSelectionBar?.openTooltip();
      this.$nextTick(() => {
        this.knowTableContainerHeight();
      });
    },
    selectionCompute(selection) {
      let tv = [];

      tv = this.multipleSelection.filter(ms =>
        this.page.list.every(c => c.id !== ms.id)
      );
      tv = _.uniqWith([...tv, ...selection], _.isEqual);

      return tv;
    },
    // 匹配选中的列
    matchSelected() {
      if (!this.multipleSelection.length) return;

      const selected =
        this.page.list.filter(c => {
          if (this.multipleSelection.some(sc => sc.id === c.id)) {
            this.multipleSelection = this.multipleSelection.filter(
              sc => sc.id !== c.id
            );
            this.multipleSelection.push(c);
            return c;
          }
        }) || [];

      this.$nextTick(() => {
        this.toggleSelection(selected);
      });
    },
    toggleSelection(rows) {
      let isNotOnCurrentPage = false;
      let item = undefined;
      let row = undefined;

      if (rows) {
        for (let i = 0; i < rows.length; i++) {
          row = rows[i];
          isNotOnCurrentPage = this.page.list.every(item => {
            return item.id !== row.id;
          });
          if (isNotOnCurrentPage) return;
        }
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
        this.multipleSelection = [];
      }
    },
    // 当拖动表头改变了列的宽度的时候会触发该事件
    headerDragend(newWidth, oldWidth, column, event) {
      let data = this.columns
        .map(item => {
          if (item.fieldName === column.property) {
            item.width = column.width;
          }
          return item;
        })
        .map(item => {
          return {
            field: item.field,
            show: item.show,
            width: item.width,
          };
        });
      this.modifyColumnStatus({ type: 'column', data });
    },
    /**
     * @description 修改选择列设置
     * @param {Object} event 事件对象
     */
    modifyColumnStatus(event) {
      let columns = event.data || [],
        colMap = columns.reduce(
          (acc, col) => (acc[col.field] = col) && acc,
          {}
        );
      this.columns.forEach(col => {
        let newCol = colMap[col.field];
        if (null != newCol) {
          this.$set(col, 'show', newCol.show);
          this.$set(col, 'width', newCol.width);
        }
      });

      this.saveColumnStatusToStorage();
    },
    // 构建列表表头
    buildColumns() {
      const localStorageData = this.getLocalStorageData();
      let columnStatus = localStorageData.columnStatus || [];

      let localColumns = columnStatus
        .map(i => (typeof i == 'string' ? { field: i, show: true } : i))
        .reduce((acc, col, currentIndex) => {
          acc[col.field] = {
            field: col,
            index: currentIndex,
          };
          return acc;
        }, {});
      let fields = [...this.memberFields].sort((a, b) => a.orderId - b.orderId);
      if (Array.isArray(columnStatus) && columnStatus.length > 0) {
        fields = this.buildSortFields(fields, localColumns);
      }

      this.columns = fields
        .filter(v => v.show)
        .map(field => {
          let sortable = false;
          let minWidth = 120;

          if (field.displayName.length > 4) {
            minWidth = field.displayName.length * 20;
          }

          if (
            field.formType === 'datetime' ||
            [
              'updateTime',
              'createTime',
            ].includes(field.fieldName)
          ) {
            minWidth = 160;
          }

          return {
            ...field,
            label: field.displayName,
            field: field.fieldName,
            formType: field.formType,
            minWidth: typeof minWidth == 'number' ? minWidth : `${minWidth}px`,
            sortable,
            isSystem: field.isSystem,
          };
        })
        .map(col => {
          let show = col.show === true;
          let { width } = col;
          let localField =
            (localColumns[col.field] && localColumns[col.field].field) || null;

          let fixLeft = localField?.fixLeft || null;

          if (null != localField) {
            width =
              typeof localField.width == 'number'
                ? `${localField.width}px`
                : `${localField.width}`.indexOf('px')
                ? localField.width
                : '';
            show = localField.show !== false;
          }

          col.show = show;
          col.width = width;
          col.type = 'column';
          col['fixLeft'] = fixLeft && 'left';
          return col;
        });
    },
    buildSortFields(originFields = [], fieldsMap = {}) {
      let fields = [];
      let unsortedFields = [];

      originFields.forEach(originField => {
        let { fieldName } = originField;
        let field = fieldsMap[fieldName];

        if (field) {
          let { index } = field;
          fields[index] = originField;
        } else {
          unsortedFields.push(originField);
        }
      });

      // 存储列数据之后，如果存在列被删除的情况，可能产生空值，需要过滤，否则其他地方没做判断会报错
      return fields.filter(v => v).concat(unsortedFields);
    },
    /**
     * @description 构建导出参数
     * @return {Object} 导出参数
     */
    buildExportParams(checkedMap, ids, exportOneRow) {
      const { memberExport } = checkedMap;
      const exportAll = !ids || !ids.length;

      const params = {
        checked: memberExport.join(','),
        searchModel: {
          ...this.searchModel,
          ids,
          ...this.advancedSearchParams,
        },
        exportTotal: exportAll
          ? this.page.totalElements
          : this.selectedIds.length,
      };

      return params;
    },
    /**
     * @description 检测导出条数
     * @return {String | null}
     */
    checkExportCount(ids, max) {
      let exportAll = !ids || ids.length == 0;
      return exportAll && this.page.totalElements > max
        ? this.$t('common.base.exportModal.oversizeTips', {size: '5000'})
        : null;
    },
    getLocalStorageData() {
      const dataStr = storageGet('goods_list_localStorage') || '{}';
      return JSON.parse(dataStr);
    },
    saveDataToStorage(key, value) {
      const data = this.getLocalStorageData();
      data[key] = value;
      storageSet('goods_list_localStorage', JSON.stringify(data));
    },
    saveColumnStatusToStorage() {
      const localStorageData = this.getLocalStorageData();
      let columnsStatus = null;

      // 判断是否存储选择列
      const columnsList = this.columns.map(c => ({
        field: c.fieldName,
        show: c.show,
        width: c.width,
        fixLeft: c.fixLeft,
      }));

      if (localStorageData.columnStatus) {
        localStorageData.columnStatus = columnsList;
        columnsStatus = localStorageData.columnStatus;
      } else {
        columnsStatus = columnsList;
      }

      this.saveDataToStorage('columnStatus', columnsStatus);
    },
    /**
     * @description 修改选择列设置
     * @param {Object} event 事件对象
     */
    saveColumnStatus(event) {
      let columns = event.data || [];

      this.columns = [];

      this.$nextTick(() => {
        this.$set(this, 'columns', columns.slice());
        this.tableKey = (Math.random() * 1000) >> 2;
        this.saveColumnStatusToStorage();
      });
      this.$message.success(this.$t('common.base.saveSuccess'));
    },
    /**
     * @des 获取列表当前的可滚动高度
     */
    knowTableContainerHeight() {
      let min = 440;
      try {
        let window_ = window.innerHeight;
        let header = this.$refs.tableHeaderContainer?.offsetHeight || 0;
        let do_ = this.$refs.tableDoContainer?.offsetHeight || 0;
        let footer = this.$refs.tableFooterContainer?.offsetHeight || 0;
        let selection = this.$refs.BaseSelectionBarComponent?.offsetHeight || 0;
        min =
          window_ - header * 1 - do_ * 1 - footer * 1 - selection * 1 - 24 - 12;
        min = min > 440 ? min : 440;
      } catch (error) {
        console.warn(error, 'error try catch');
      }
      this.$set(this, 'tableContainerHeight', `${min}px`);
    },
    handleCurrentChange(pageNum) {
      this.searchModel.pageNum = pageNum;
      this.handleSearch();
    },
    handleSizeChange(pageSize) {
      this.searchModel.pageSize = pageSize;
      this.searchModel.pageNum = 1;
      this.handleSearch();
    },
    async handleSwitchChange(row,value) {
      const { code, message,success } = await editMembershipEnabled({
        id: row.id,
        enabled: value,
      });
      if (success) {
        this.handleSearch();
      } else {
        this.$message.error(message)
      }
    }
  },
};
</script>

<style lang="scss" scoped>
@import '@src/assets/scss/common-list.scss';

.goods-list-container {
  height: 100%;
  padding: 10px;
  overflow: auto;

  .goods-list-search-group-container {
    padding: 16px;
    border-radius: 3px;
    .base-search {
      background: #fff;
      border-radius: 3px;
      font-size: 14px;
      display: flex;
      justify-content: space-between;

      .goods-list-base-search-group {
        display: flex;
        justify-content: space-between;

        .el-input {
          width: 400px;
        }

        a {
          line-height: 33px;
        }
      }

      .advanced-search-visible-btn {
        font-size: 14px;
        line-height: 31px;
        @include fontColor();
        border-color: $color-primary;
        background: #fff;
        padding: 0 13px;
        white-space: nowrap;
        &:hover {
          cursor: pointer;
        }

        i {
          font-size: 16px;
        }
      }
    }
  }

  .task-list {
    &-header {
      background: #ffffff;
      box-shadow: 0px 0px 0px 0px rgba(0, 0, 0, 0.06);
      border-radius: 4px;
      margin-bottom: 12px;
      border-top: none;

      &-search {
        width: 100%;
        display: flex;
        justify-content: flex-end;
        align-items: flex-start;
        // padding: 16px;
        .advanced-search-visible-btn {
          // width: 98px;
          height: 32px;
          border-radius: 4px;
          font-size: 14px;
          @include fontColor();
          line-height: 32px;
          text-align: center;
          cursor: pointer;
          white-space: nowrap;
          margin-left: 0;

          i {
            font-size: 16px;
          }
        }

        .base-search-group {
          .el-input {
            width: 400px !important;
            input {
              border-radius: 4px 0 0 4px;
            }
          }
        }

        .customize-filter-view {
          margin-bottom: 16px;
        }
      }

      &-nav {
        padding-top: 16px;
        .task-filter-item {
          display: flex;
        }
        > div {
          position: relative;
          cursor: pointer;
          .state {
            padding-top: 4px;
            width: 50px;
            font-weight: 500;
          }
          .element-icon {
            position: absolute;
            right: 12px;
            top: 6px;
            span {
              color: rgba(0, 0, 0, 0.65);
            }
          }
          .list {
            padding-right: 50px;
            flex: 1;
            overflow: hidden;
            .list-item {
              > div {
                font-size: 13px;
                max-width: 160px;
                overflow-y: hidden;
                color: #808080;
                padding: 4px 8px;
                margin: 0 12px 8px 0;
                white-space: nowrap;
                overflow: hidden;
                &:hover {
                  color: $color-primary;

                }
              }
            }
          }
        }
      }
    }
  }

  .task-list-header-search {
    form {
      justify-content: flex-end;
    }
  }

  .task-padding-0 {
    padding: 0 !important;
  }

  .goods-list-section {
    margin-top: 12px;
    padding-top: 0;

    .operation-bar-container {
      background: #fff;
      border-radius: 4px 4px 0 0;
      display: flex;
      justify-content: space-between;
      padding: 16px 16px 0;

      .el-dropdown-btn {
        padding: 0 15px;
        line-height: 31px;
        display: inline-block;
        background: $color-primary-light-9;
        color: $text-color-primary;
        outline: none;
        margin-left: 5px;
        .iconfont {
          margin-left: 5px;
          // font-size: 12px;
        }

        &:hover {
          cursor: pointer;
          color: #fff;
          background: $color-primary;
        }
      }
    }
  }

  .goods-table {
    .view-detail-btn {
      @include fontColor();
    }

    .view-image {
      width: 32px;
      height: 32px;
      cursor: pointer;
    }

    .view-putaway-status {
      span {
        display: block;
        min-width: 52px;
        height: 22px;
        line-height: 22px;
        text-align: center;
        background: #00c853;
        border-radius: 11px;
        font-size: 12px;
        color: #fff;
        padding:0 8px 0 8px;
      }

      .gray-state {
        background: #bdbdbd;
      }
    }
  }

  .table-footer {
    display: flex;
    justify-content: space-between;
    padding: 0px 10px 10px 10px;
    background: #fff;
    border-radius: 0 0 3px 3px;

    .list-info {
      font-size: 13px;
      line-height: 32px;
      margin: 0;
      color: #767e89;

      .iconfont {
        position: relative;
        top: 1px;
      }

      .product-selected-count {
        color: $color-primary;
        padding: 0 3px;
        width: 15px;
        text-align: center;
        cursor: pointer;
        font-size: 13px;
      }
    }

    .el-pagination__jump {
      margin-left: 0;
    }
  }
}

.goods-list-container ::v-deep .el-table__header th {
  padding: 0;
  height: 40px;
}
// .cur-point {
//   color: $color-primary-light-6;
// }
.more-text{
  color: $color-primary;
}
.lang-select-dropdown {
  margin-top: 0!important;
  & > * {
    font-size: 13px;
    &:hover {
      color: $color-primary !important;
    }
  }
}
</style>
